package com.oswift.cms.web.reception;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import com.oswift.cms.entity.reception.Channel;
import com.oswift.cms.entity.reception.ReceptionPageUrl;
import com.oswift.cms.entity.reception.WebConfig;
import com.oswift.cms.service.IReceptionService;
import com.oswift.cms.system.cache.ReceptionPageUrlManager;
import com.oswift.cms.system.cache.WebConfigManager;
import com.oswift.cms.utils.ReceptionConstant;
import com.oswift.cms.utils.ReceptionConstant.ContentType;
import com.oswift.cms.utils.ReceptionConstant.ReceptionPageUrLState;
import com.oswift.utils.common.RegexUtils;
import com.oswift.utils.common.StringUtil;

public class BaseAction
{
    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(BaseAction.class);

    /**
     * 每页显示记录数
     */
    protected int pageRecordNum = 15;

    /**
     * 页码默认值
     */
    protected static int DEFAULT_PAGENUM = 1;

    /**
     * spring注入
     */
    @Resource
    protected IReceptionService receptionService;

    /**
     *
     * 将查询字符串解码
     *
     * @author zhuou
     * @param keyword
     *            查询字符串
     * @return 解码字符串
     */
    public String decodeKeyword(String keyword)
    {
        // 解决中文乱码的问题
        if (null != keyword)
        {
            try
            {
                keyword = new String(keyword.getBytes("ISO-8859-1"), "UTF-8");
                keyword = URLDecoder.decode(keyword, "UTF-8");
            }
            catch (UnsupportedEncodingException e)
            {
                // 异常抛弃
            }
        }
        return keyword;
    }

    /**
     * 获取站点信息
     */
    public WebConfig getWebConfig(HttpServletRequest request)
    {
        // 获取站点信息
        // 获取域名或者IP
        String webSitUrl = request.getServerName();
        WebConfig webConfigBean = WebConfigManager.getValue(webSitUrl);

        return webConfigBean;
    }

    /**
     *
     * 根据HashId获取缓存中的PageBean，// siteId+"|"+urlType+"|"+nickName
     *
     * @author zhuou
     * @param siteId
     *            站点ID
     * @param urlType
     *            url类型
     * @param nickName
     *            页面名称
     * @return PageBean
     */
    public ReceptionPageUrl getReceptionPageUrlFun(int siteId, int urlType,
            String nickName)
    {
        // 栏目Id+"|"+单位Id+"|"+功能页面Id
        StringBuffer sb = new StringBuffer();
        sb.append(siteId);
        sb.append("|");
        sb.append(urlType);
        sb.append("|");
        sb.append(nickName);
        ReceptionPageUrl bean = ReceptionPageUrlManager.getValue(sb.toString());
        return bean;
    }

    /**
     *
     * 获取jsp文件路径
     *
     * @author zhuou
     * @param page
     *            页面相对userfile文件夹路径
     * @siteId 站点id
     * @return String
     */
    public String pagePath(String page, int siteId)
    {
        StringBuffer pagePath = new StringBuffer();
        pagePath.append(ReceptionConstant.USERFILE);
        pagePath.append(ReceptionConstant.FILE_SEPARATOR);
        pagePath.append(ReceptionConstant.USERFILENAME);
        pagePath.append(siteId);
        pagePath.append(ReceptionConstant.FILE_SEPARATOR);
        pagePath.append(page);

        return pagePath.toString();
    }

    /**
     *
     * 获取站点资源文件存放路径
     *
     * @author zhuou
     * @param siteId
     *            站点Id
     * @return 文件存放路径
     */
    public String webPath(HttpServletRequest request, int siteId)
    {
        StringBuffer webPath = new StringBuffer();
        webPath.append(request.getContextPath());
        webPath.append("/");
        webPath.append(ReceptionConstant.USERFILE);
        webPath.append("/");
        webPath.append(ReceptionConstant.USERFILENAME);
        webPath.append(siteId);

        return webPath.toString();
    }

    /**
     *
     * 获取站点配置的错误页面路径
     *
     * @author zhuou
     * @param webConfig
     *            站点配置信息
     * @return String
     */
    public String getErrorPage(WebConfig webConfig)
    {
        // 获取错误页面
        String errorPage = ReceptionConstant.errorPagePath;
        if (!StringUtil.isEmpty(webConfig.getErrorPagePath()))
        {
            errorPage = webConfig.getErrorPagePath();
        }

        return errorPage;
    }

    /**
     * 列表1 list.html请求处理页面
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param pageName
     *            页面别名
     * @param nowPage
     *            当前第几页
     * @return ModelAndView
     */
    public ModelAndView getList(HttpServletRequest request, String pageName,
            int nowPage)
    {
        ModelAndView mv = null;
        WebConfig webConfig = this.getWebConfig(request);
        int siteId = webConfig.getSiteId();

        // 判断页面别名
        if (StringUtil.isEmpty(pageName))
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        ReceptionPageUrl bean = this.getReceptionPageUrlFun(siteId,
                ReceptionPageUrLState.LIST, pageName.trim());
        // 跳转到错误页面
        if (null == bean)
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }
        mv = new ModelAndView(pagePath(bean.getJspPath(), siteId));
        mv.addObject("webConfig", webConfig);
        mv.addObject("webPath", webPath(request, siteId));
        mv.addObject("contextPath", request.getContextPath());
        mv.addObject("nowPage", nowPage);
        mv.addObject("pageName", pageName);
        mv.addObject("request", request);

        return mv;
    }

    /**
     *
     * url：/页面别名/type_类型_list_第几页.html,例如：/article/type_new_list_1.html
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param pageName
     *            页面别名
     * @param contentType
     *            内容类型
     * @param nowPage
     *            当前第几页
     * @return ModelAndView
     */
    public ModelAndView getTypeList(HttpServletRequest request,
            String pageName, String contentType, int nowPage)
    {
        ModelAndView mv = null;
        WebConfig webConfig = this.getWebConfig(request);
        int siteId = webConfig.getSiteId();

        // 判断页面别名
        if (StringUtil.isBlank(pageName))
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        // 如果没有值则默认最新内容类型
        if (StringUtil.isEmpty(contentType))
        {
            contentType = ContentType.NEW;
        }

        ReceptionPageUrl bean = this.getReceptionPageUrlFun(siteId,
                ReceptionPageUrLState.LIST_TYPE, pageName.trim());
        // 跳转到错误页面
        if (null == bean)
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        mv = new ModelAndView(pagePath(bean.getJspPath(), siteId));

        mv.addObject("webConfig", webConfig);
        mv.addObject("contentType", contentType);
        mv.addObject("nowPage", nowPage);
        mv.addObject("webPath", webPath(request, siteId));
        mv.addObject("contextPath", request.getContextPath());
        mv.addObject("pageName", pageName);
        mv.addObject("request", request);
        return mv;
    }

    /**
     *
     * url:/页面别名/栏目别名/list_第几页.html,例如：/pic/girl/list_1.html
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param pageName
     *            页面别名
     * @param channel
     *            栏目id或者栏目别名
     * @param nowPage
     *            当前第几页
     * @return ModelAndView
     */
    public ModelAndView getChannelList(HttpServletRequest request,
            String pageName, String channel, int nowPage)
    {
        ModelAndView mv = null;
        WebConfig webConfig = this.getWebConfig(request);
        int companyId = webConfig.getCompanyId();
        int siteId = webConfig.getSiteId();

        // 判断页面别名
        if (StringUtil.isEmpty(pageName))
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        ReceptionPageUrl bean = this.getReceptionPageUrlFun(siteId,
                ReceptionPageUrLState.CHANNEL_LIST, pageName.trim());
        // 跳转到错误页面
        if (null == bean)
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        try
        {
            Channel currentChannel = null;
            // 如果不是数字，则证明是别名，根据别名查询出id
            if (!RegexUtils.isNumber(channel))
            {
                currentChannel = receptionService.getChannelByNickName(
                        companyId, channel);
            }
            else
            {
                currentChannel = receptionService.getChannelById(Integer
                        .valueOf(channel));
            }
            // 证明没有此栏目
            if (null == currentChannel)
            {
                mv = new ModelAndView(getErrorPage(webConfig));
                return mv;
            }
            mv = new ModelAndView(pagePath(bean.getJspPath(), siteId));
            mv.addObject("webConfig", webConfig);
            mv.addObject("webPath", webPath(request, siteId));
            mv.addObject("nowPage", nowPage);
            mv.addObject("currentChannel", currentChannel);
            mv.addObject("contextPath", request.getContextPath());
            mv.addObject("pageName", pageName);
            mv.addObject("request", request);
        }
        catch (Exception e)
        {
            log.error(
                    "The 'index' of front channelList's page is exception，companyId="
                            + companyId, e);
            mv = new ModelAndView(getErrorPage(webConfig));
        }
        return mv;
    }

    /**
     *
     * url:/页面别名/栏目别名/type_类型_list_第几页.html,例如：/pic/girl/type_new_list_1.html
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param pageName
     *            页面别名
     * @param channel
     *            栏目别名或者栏目id
     * @param contentType
     *            内容类型
     * @param nowPage
     *            当前第几页
     * @return ModelAndView
     */
    public ModelAndView getChannelTypeList(HttpServletRequest request,
            String pageName, String channel, String contentType, int nowPage)
    {
        ModelAndView mv = null;
        WebConfig webConfig = this.getWebConfig(request);
        int companyId = webConfig.getCompanyId();
        int siteId = webConfig.getSiteId();

        // 判断页面别名
        if (StringUtil.isEmpty(pageName))
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        ReceptionPageUrl bean = this.getReceptionPageUrlFun(siteId,
                ReceptionPageUrLState.CHANNEL_LIST_TYPE, pageName.trim());
        // 跳转到错误页面
        if (null == bean)
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        // 如果没有值则默认最新内容类型
        if (StringUtil.isBlank(contentType))
        {
            contentType = ContentType.NEW;
        }
        try
        {
            Channel currentChannel = null;
            // 如果不是数字，则证明是别名，根据别名查询出id
            if (!RegexUtils.isNumber(channel))
            {
                currentChannel = receptionService.getChannelByNickName(
                        companyId, channel);
            }
            else
            {
                currentChannel = receptionService.getChannelById(Integer
                        .valueOf(channel));
            }
            // 证明没有此栏目
            if (null == currentChannel)
            {
                mv = new ModelAndView(getErrorPage(webConfig));
                return mv;
            }
            mv = new ModelAndView(pagePath(bean.getJspPath(), siteId));
            mv.addObject("webConfig", webConfig);
            mv.addObject("contentType", contentType);
            mv.addObject("nowPage", nowPage);
            mv.addObject("webPath", webPath(request, siteId));
            mv.addObject("currentChannel", currentChannel);
            mv.addObject("contextPath", request.getContextPath());
            mv.addObject("pageName", pageName);
            mv.addObject("request", request);
        }
        catch (Exception e)
        {
            log.error(
                    "The 'index' of front channelTypeList's page is exception，companyId="
                            + companyId, e);
            mv = new ModelAndView(getErrorPage(webConfig));
        }
        return mv;
    }

    /**
     *
     * 内容详情url:/article/100/detail.html
     *
     * @author zhuou
     * @param request
     *            HttpServletRequest
     * @param pageName
     *            页面别名
     * @return ModelAndView
     */
    public ModelAndView getDetail(HttpServletRequest request, String pageName,
            String contentId)
    {
        ModelAndView mv = null;
        WebConfig webConfig = this.getWebConfig(request);
        int siteId = webConfig.getSiteId();

        // 判断页面别名
        if (StringUtil.isBlank(pageName))
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        ReceptionPageUrl bean = this.getReceptionPageUrlFun(siteId,
                ReceptionPageUrLState.DETAIL, pageName.trim());
        // 跳转到错误页面
        if (null == bean)
        {
            mv = new ModelAndView(getErrorPage(webConfig));
            return mv;
        }

        try
        {
            long iContentId = 0;
            Channel currentChannel = null;
            if (RegexUtils.isNumber(contentId))
            {
                iContentId = Long.valueOf(contentId);
                currentChannel = receptionService
                        .getChannelByCommonModelId(iContentId);
            }

            // 如果页面有分页
            int iNowPage = ReceptionConstant.DEFAULT_PAGENUM;
            String nowPage = request.getParameter("p");
            if (!StringUtil.isBlank(nowPage))
            {
                if (RegexUtils.isNumber(nowPage))
                {
                    iNowPage = Integer.valueOf(nowPage);
                }
            }

            mv = new ModelAndView(pagePath(bean.getJspPath(), siteId));
            mv.addObject("webConfig", webConfig);
            mv.addObject("webPath", webPath(request, siteId));
            mv.addObject("currentChannel", currentChannel);
            mv.addObject("contextPath", request.getContextPath());
            mv.addObject("contentId", iContentId);
            mv.addObject("pageName", pageName);
            mv.addObject("nowPage", iNowPage);
            mv.addObject("request", request);
        }
        catch (Exception e)
        {
            log.error(
                    "The 'index' of front detail's page is exception，companyId="
                            + webConfig.getCompanyId(), e);
            mv = new ModelAndView(getErrorPage(webConfig));
        }
        return mv;
    }

    public void setReceptionService(IReceptionService receptionService)
    {
        this.receptionService = receptionService;
    }
}
